package utilities
{
	import flash.display.Stage;
	import flash.events.KeyboardEvent;
	/**
	 * ...
	 * @author Leong  Shi Yun
	 */
	public class KeyboardInputManager
	{
		/***** private var/const *****/
		private const KEYS_SIZE:uint = 256;
		
		private static var m_aPrev:Array = null;
		private static var m_aCurr:Array = null;
		private static var m_stage:Stage = null;
		
		/***** public functions *****/
		public function KeyboardInputManager(stage:Stage):void
		{
			initialize(stage);
		}
		
		public function initialize(stage:Stage):void
		{
			m_stage = stage;
			
			m_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
			m_stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
			
			m_aPrev = new Array(KEYS_SIZE);
			m_aCurr = new Array(KEYS_SIZE);
			
			for (var i:uint = 0; i < KEYS_SIZE; ++i)
			{
				m_aPrev[i] = 0;
				m_aCurr[i] = 0;
			}
			
		}
		
		public function destroy():void
		{
			m_stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDown);
			m_stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp);
			m_stage = null;
		}
		
		public static function isPressed(keyCode:uint):Boolean
		{
			return m_aCurr[keyCode];
		}
		
		public static function isTriggered(keyCode:uint):Boolean
		{
			return m_aCurr[keyCode] && !m_aPrev[keyCode];
		}
		
		public static function isReleased(keyCode:uint):Boolean
		{
			return !m_aCurr[keyCode] && m_aPrev[keyCode];
		}
		
		/***** private functions *****/
		private static function keyDown(ke:KeyboardEvent):void
		{
			m_aCurr[ke.keyCode] = 1; // true
		}
		
		private static function keyUp(ke:KeyboardEvent):void
		{
			m_aCurr[ke.keyCode] = 0; // false
		}
		
		public function update():void
		{
			for (var i:uint = 0; i < KEYS_SIZE; ++i)
			{
				m_aPrev[i] = m_aCurr[i];
			}
			
		}
		
	}

}